/**
 * 作者：陈文斌 on 2019/1/15.
 * 邮箱：chen_wennbin@163.com
 * 版本：v1.0
 */

import 'package:flutter/material.dart';
import 'package:crm/constant/constant.dart';
import 'package:crm/model/VisitorRecord/visitor_type_model.dart';
import 'package:crm/viewModel/VisitorRecord/visitor_record_view_model.dart';
import 'package:crm/view/Tile/list_tile_normal.dart';
import 'package:crm/view/AppBar/custom_app_bar.dart';

const String Title = '拜访类型';

class VisitorTypePage extends StatefulWidget {
  final Function confirmCallback;

  @override
  VisitorTypePage({
    Key key,
    this.confirmCallback,
  }) : super(key: key);

  State<StatefulWidget> createState() {
    return _VisitorTypePageState();
  }
}

class _VisitorTypePageState extends State<VisitorTypePage> {
  List<VisitorTypeModel> _visitorTypes = List<VisitorTypeModel>();
  bool _isPerformingRequest = false;

  // 选中的VisitorType，默认为：0
  int _selVisitorTypeIndex = 0;

  _get() async {
    if (!_isPerformingRequest) {
      _isPerformingRequest = true;

      VisitorRecordVM().getVisitorTypes(
        callback: (visitorTypes) {
          // 请求成功
          _isPerformingRequest = false;
          _visitorTypes = visitorTypes;
          if (!mounted) return;
          setState(() {});
        },
        errorCallback: (errMsg) => print(errMsg),
      );
    }
  }

  @override
  void initState() {
    super.initState();
    _get();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        title: Title,
        actions: <Widget>[
          MaterialButton(
            onPressed: () {
              if (widget.confirmCallback != null && _visitorTypes.length > 0) {
                widget.confirmCallback(_visitorTypes[_selVisitorTypeIndex]);
              }
              Navigator.pop(context);
            },
            child: Text(
              '确定',
              style: AppStyles.actionsTitleStyle,
            ),
            splashColor: Colors.transparent,
            highlightColor: Colors.transparent,
          )
        ],
      ),
      body: ListView.builder(
        itemCount: _visitorTypes.length,
        itemBuilder: (context, i) {
          VisitorTypeModel _visitorType = _visitorTypes[i];
          bool _isSelect = i == _selVisitorTypeIndex;
          return ListTileNormal(
            title: Text(_visitorType.content),
            trailing: Offstage(
              offstage: !_isSelect,
              child: Icon(
                Icons.done,
                color: AppColors.MainColor,
                size: 20,
              ),
            ),
            arrowVisible: true,
            onTap: () {
              _selVisitorTypeIndex = i;
              if (!mounted) return;
              setState(() {});
            },
          );
        },
      ),
    );
  }
}
